<!DOCTYPE html><html lang="zh-CN" data-theme="light"><head><meta name="referrer" content="no-referrer"><meta charset="UTF-8"><meta http-equiv="X-UA-Compatible" content="IE=edge"><meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no"><title>09.Python文件操作 | 小妖笔记</title><meta name="author" content="小妖"><meta name="copyright" content="小妖"><meta name="format-detection" content="telephone=no"><meta name="theme-color" content="#ffffff"><meta name="description" content="Python入门课程   文件操作 章节目录 [!WARNING|label:本章需要学习的内容]   文件的编码 文件的读取 文件的写入 文件的追加 文件操作综合案例  文件的编码UTF-8是目前全球通用的编码格式 除非有特殊需求，否则，一律以UTF-8格式进行文件编码即可。  [!note|style:callout|label:总结]1. 什么是编码？编码就是一种规则集合，记录了内容和二进制">
<meta property="og:type" content="article">
<meta property="og:title" content="09.Python文件操作">
<meta property="og:url" content="http://grace.666443.xyz/posts/66462a4e.html">
<meta property="og:site_name" content="小妖笔记">
<meta property="og:description" content="Python入门课程   文件操作 章节目录 [!WARNING|label:本章需要学习的内容]   文件的编码 文件的读取 文件的写入 文件的追加 文件操作综合案例  文件的编码UTF-8是目前全球通用的编码格式 除非有特殊需求，否则，一律以UTF-8格式进行文件编码即可。  [!note|style:callout|label:总结]1. 什么是编码？编码就是一种规则集合，记录了内容和二进制">
<meta property="og:locale" content="zh_CN">
<meta property="og:image" content="https://p.ananas.chaoxing.com/star3/origin/0ceb37b5df0be961614fe246b9d2048a.png">
<meta property="article:published_time" content="2022-12-08T11:58:50.000Z">
<meta property="article:modified_time" content="2022-12-08T12:08:47.627Z">
<meta property="article:author" content="小妖">
<meta property="article:tag" content="笔记 开发">
<meta name="twitter:card" content="summary">
<meta name="twitter:image" content="https://p.ananas.chaoxing.com/star3/origin/0ceb37b5df0be961614fe246b9d2048a.png"><link rel="shortcut icon" href="/img/favicon.png"><link rel="canonical" href="http://grace.666443.xyz/posts/66462a4e"><link rel="preconnect" href="//cdn.jsdelivr.net"/><link rel="preconnect" href="//busuanzi.ibruce.info"/><link rel="stylesheet" href="/css/index.css"><link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/@fortawesome/fontawesome-free/css/all.min.css" media="print" onload="this.media='all'"><link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/node-snackbar/dist/snackbar.min.css" media="print" onload="this.media='all'"><link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/@fancyapps/ui/dist/fancybox.min.css" media="print" onload="this.media='all'"><script>const GLOBAL_CONFIG = { 
  root: '/',
  algolia: undefined,
  localSearch: {"path":"/search.xml","preload":true,"languages":{"hits_empty":"找不到您查询的内容：${query}"}},
  translate: undefined,
  noticeOutdate: undefined,
  highlight: {"plugin":"highlighjs","highlightCopy":true,"highlightLang":true,"highlightHeightLimit":false},
  copy: {
    success: '复制成功',
    error: '复制错误',
    noSupport: '浏览器不支持'
  },
  relativeDate: {
    homepage: false,
    post: false
  },
  runtime: '',
  date_suffix: {
    just: '刚刚',
    min: '分钟前',
    hour: '小时前',
    day: '天前',
    month: '个月前'
  },
  copyright: undefined,
  lightbox: 'fancybox',
  Snackbar: {"chs_to_cht":"你已切换为繁体","cht_to_chs":"你已切换为简体","day_to_night":"你已切换为深色模式","night_to_day":"你已切换为浅色模式","bgLight":"#49b1f5","bgDark":"#1f1f1f","position":"bottom-left"},
  source: {
    justifiedGallery: {
      js: 'https://cdn.jsdelivr.net/npm/flickr-justified-gallery/dist/fjGallery.min.js',
      css: 'https://cdn.jsdelivr.net/npm/flickr-justified-gallery/dist/fjGallery.min.css'
    }
  },
  isPhotoFigcaption: false,
  islazyload: false,
  isAnchor: false
}</script><script id="config-diff">var GLOBAL_CONFIG_SITE = {
  title: '09.Python文件操作',
  isPost: true,
  isHome: false,
  isHighlightShrink: false,
  isToc: true,
  postUpdate: '2022-12-08 20:08:47'
}</script><noscript><style type="text/css">
  #nav {
    opacity: 1
  }
  .justified-gallery img {
    opacity: 1
  }

  #recent-posts time,
  #post-meta time {
    display: inline !important
  }
</style></noscript><script>(win=>{
    win.saveToLocal = {
      set: function setWithExpiry(key, value, ttl) {
        if (ttl === 0) return
        const now = new Date()
        const expiryDay = ttl * 86400000
        const item = {
          value: value,
          expiry: now.getTime() + expiryDay,
        }
        localStorage.setItem(key, JSON.stringify(item))
      },

      get: function getWithExpiry(key) {
        const itemStr = localStorage.getItem(key)

        if (!itemStr) {
          return undefined
        }
        const item = JSON.parse(itemStr)
        const now = new Date()

        if (now.getTime() > item.expiry) {
          localStorage.removeItem(key)
          return undefined
        }
        return item.value
      }
    }
  
    win.getScript = url => new Promise((resolve, reject) => {
      const script = document.createElement('script')
      script.src = url
      script.async = true
      script.onerror = reject
      script.onload = script.onreadystatechange = function() {
        const loadState = this.readyState
        if (loadState && loadState !== 'loaded' && loadState !== 'complete') return
        script.onload = script.onreadystatechange = null
        resolve()
      }
      document.head.appendChild(script)
    })
  
      win.activateDarkMode = function () {
        document.documentElement.setAttribute('data-theme', 'dark')
        if (document.querySelector('meta[name="theme-color"]') !== null) {
          document.querySelector('meta[name="theme-color"]').setAttribute('content', '#0d0d0d')
        }
      }
      win.activateLightMode = function () {
        document.documentElement.setAttribute('data-theme', 'light')
        if (document.querySelector('meta[name="theme-color"]') !== null) {
          document.querySelector('meta[name="theme-color"]').setAttribute('content', '#ffffff')
        }
      }
      const t = saveToLocal.get('theme')
    
          if (t === 'dark') activateDarkMode()
          else if (t === 'light') activateLightMode()
        
      const asideStatus = saveToLocal.get('aside-status')
      if (asideStatus !== undefined) {
        if (asideStatus === 'hide') {
          document.documentElement.classList.add('hide-aside')
        } else {
          document.documentElement.classList.remove('hide-aside')
        }
      }
    
    const detectApple = () => {
      if(/iPad|iPhone|iPod|Macintosh/.test(navigator.userAgent)){
        document.documentElement.classList.add('apple')
      }
    }
    detectApple()
    })(window)</script><meta name="generator" content="Hexo 5.4.2"></head><body><div id="sidebar"><div id="menu-mask"></div><div id="sidebar-menus"><div class="avatar-img is-center"><img src="https://i.loli.net/2021/02/24/5O1day2nriDzjSu.png" onerror="onerror=null;src='/img/friend_404.gif'" alt="avatar"/></div><div class="sidebar-site-data site-data is-center"><a href="/archives/"><div class="headline">文章</div><div class="length-num">28</div></a><a href="/tags/"><div class="headline">标签</div><div class="length-num">2</div></a><a href="/categories/"><div class="headline">分类</div><div class="length-num">7</div></a></div><hr/><div class="menus_items"><div class="menus_item"><a class="site-page" href="/"><i class="fa-fw fas fa-home"></i><span> 首页</span></a></div><div class="menus_item"><a class="site-page" href="/archives/"><i class="fa-fw fas fa-archive"></i><span> 时间轴</span></a></div><div class="menus_item"><a class="site-page" href="/tags/"><i class="fa-fw fas fa-tags"></i><span> 标签</span></a></div><div class="menus_item"><a class="site-page" href="/categories/"><i class="fa-fw fas fa-folder-open"></i><span> 分类</span></a></div><div class="menus_item"><a class="site-page group" href="javascript:void(0);"><i class="fa-fw fa fa-heartbeat"></i><span> 清单</span><i class="fas fa-chevron-down"></i></a><ul class="menus_item_child"><li><a class="site-page child" href="/music/"><i class="fa-fw fas fa-music"></i><span> 音乐</span></a></li><li><a class="site-page child" href="/photos/"><i class="fa-fw fas fa-images"></i><span> 照片</span></a></li><li><a class="site-page child" href="/movies/"><i class="fa-fw fas fa-video"></i><span> 电影</span></a></li></ul></div><div class="menus_item"><a class="site-page" href="/link/"><i class="fa-fw fas fa-link"></i><span> 友链</span></a></div><div class="menus_item"><a class="site-page" href="/about/"><i class="fa-fw fas fa-heart"></i><span> 关于</span></a></div></div></div></div><div class="post" id="body-wrap"><header class="post-bg" id="page-header" style="background-image: url('https://p.ananas.chaoxing.com/star3/origin/0ceb37b5df0be961614fe246b9d2048a.png')"><nav id="nav"><span id="blog_name"><a id="site-name" href="/">小妖笔记</a></span><div id="menus"><div id="search-button"><a class="site-page social-icon search"><i class="fas fa-search fa-fw"></i><span> 搜索</span></a></div><div class="menus_items"><div class="menus_item"><a class="site-page" href="/"><i class="fa-fw fas fa-home"></i><span> 首页</span></a></div><div class="menus_item"><a class="site-page" href="/archives/"><i class="fa-fw fas fa-archive"></i><span> 时间轴</span></a></div><div class="menus_item"><a class="site-page" href="/tags/"><i class="fa-fw fas fa-tags"></i><span> 标签</span></a></div><div class="menus_item"><a class="site-page" href="/categories/"><i class="fa-fw fas fa-folder-open"></i><span> 分类</span></a></div><div class="menus_item"><a class="site-page group" href="javascript:void(0);"><i class="fa-fw fa fa-heartbeat"></i><span> 清单</span><i class="fas fa-chevron-down"></i></a><ul class="menus_item_child"><li><a class="site-page child" href="/music/"><i class="fa-fw fas fa-music"></i><span> 音乐</span></a></li><li><a class="site-page child" href="/photos/"><i class="fa-fw fas fa-images"></i><span> 照片</span></a></li><li><a class="site-page child" href="/movies/"><i class="fa-fw fas fa-video"></i><span> 电影</span></a></li></ul></div><div class="menus_item"><a class="site-page" href="/link/"><i class="fa-fw fas fa-link"></i><span> 友链</span></a></div><div class="menus_item"><a class="site-page" href="/about/"><i class="fa-fw fas fa-heart"></i><span> 关于</span></a></div></div><div id="toggle-menu"><a class="site-page"><i class="fas fa-bars fa-fw"></i></a></div></div></nav><div id="post-info"><h1 class="post-title">09.Python文件操作</h1><div id="post-meta"><div class="meta-firstline"><span class="post-meta-date"><i class="fa-fw post-meta-icon far fa-calendar-alt"></i><span class="post-meta-label">发表于</span><time datetime="2022-12-08T11:58:50.000Z" title="发表于 2022-12-08 19:58:50">2022-12-08</time></span><span class="post-meta-categories"><span class="post-meta-separator">|</span><i class="fas fa-inbox fa-fw post-meta-icon"></i><a class="post-meta-categories" href="/categories/python%E5%9F%BA%E7%A1%80/">python基础</a></span></div><div class="meta-secondline"><span class="post-meta-separator">|</span><span class="post-meta-pv-cv" id="" data-flag-title="09.Python文件操作"><i class="far fa-eye fa-fw post-meta-icon"></i><span class="post-meta-label">阅读量:</span><span id="busuanzi_value_page_pv"><i class="fa-solid fa-spinner fa-spin"></i></span></span></div></div></div></header><main class="layout" id="content-inner"><div id="post"><article class="post-content" id="article-container"><h1 id="Python入门课程-文件操作"><a href="#Python入门课程-文件操作" class="headerlink" title="Python入门课程   文件操作"></a>Python入门课程   文件操作</h1><hr>
<h2 id="章节目录"><a href="#章节目录" class="headerlink" title="章节目录"></a><strong>章节目录</strong></h2><blockquote>
<p>[!WARNING|label:本章需要学习的内容]</p>
</blockquote>
<ul>
<li>文件的编码</li>
<li>文件的读取</li>
<li>文件的写入</li>
<li>文件的追加</li>
<li>文件操作综合案例</li>
</ul>
<h2 id="文件的编码"><a href="#文件的编码" class="headerlink" title="文件的编码"></a><strong>文件的编码</strong></h2><p>UTF-8是目前全球通用的编码格式</p>
<p>除非有特殊需求，否则，一律以UTF-8格式进行文件编码即可。</p>
<blockquote>
<p>[!note|style:callout|label:总结]1. 什么是编码？<br><br>编码就是一种规则集合，记录了内容和二进制间进行相互转换的逻辑。<br><br>编码有许多中，我们最常用的是UTF-8编码<br><br>2. 为什么需要使用编码？<br><br>计算机只认识0和1，所以需要将内容翻译成0和1才能保存在计算机中。<br><br>同时也需要编码， 将计算机保存的0和1，反向翻译回可以识别的内容。<br></p>
</blockquote>
<h2 id="文件的读取"><a href="#文件的读取" class="headerlink" title="文件的读取"></a><strong>文件的读取</strong></h2><blockquote>
<p>学习目标：<br/> ① 了解文件操作的作用  <br/> ②掌握文件的打开、读取、关闭操作</p>
</blockquote>
<p><img src="https://img-blog.csdnimg.cn/72a5a8be87164826b7b7f74ce0bcea0a.jpeg" alt="1"><br><img src="https://img-blog.csdnimg.cn/65b5bc6e6f2d42dd84a374fa99637054.jpeg" alt="2"><br><img src="https://img-blog.csdnimg.cn/29ab66e07cbc46c9a5047576785b125b.jpeg" alt="3"><br><img src="https://img-blog.csdnimg.cn/647f72a790154fdeac603485d0dfe711.jpeg" alt="4"><br><img src="https://img-blog.csdnimg.cn/bb9f488041cd4dd99ce465d3674c9b17.jpeg" alt="5"><br><img src="https://img-blog.csdnimg.cn/264ad1e2aee74425ad6e56987c81c5c9.jpeg" alt="6"><br><img src="https://img-blog.csdnimg.cn/d2f76c61f2294a2580a28d2f668094b6.jpeg" alt="7"><br><img src="https://img-blog.csdnimg.cn/d88c53da4fb9408ab1d8b0185500c07f.jpeg" alt="8"><br><img src="https://img-blog.csdnimg.cn/304be6cfdd1e45309f077e65f5e9fad4.jpeg" alt="9"><br><img src="https://img-blog.csdnimg.cn/744f35fc407842ce94b6cc964018e1ab.jpeg" alt="10"><br><img src="https://img-blog.csdnimg.cn/47c6fec7793a4381b55697fee0fe612e.jpeg" alt="11"></p>
<blockquote>
<p>代码</p>
</blockquote>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br><span class="line">62</span><br><span class="line">63</span><br><span class="line">64</span><br><span class="line">65</span><br><span class="line">66</span><br><span class="line">67</span><br><span class="line">68</span><br><span class="line">69</span><br><span class="line">70</span><br><span class="line">71</span><br><span class="line">72</span><br><span class="line">73</span><br><span class="line">74</span><br><span class="line">75</span><br><span class="line">76</span><br><span class="line">77</span><br><span class="line">78</span><br><span class="line">79</span><br><span class="line">80</span><br><span class="line">81</span><br><span class="line">82</span><br><span class="line">83</span><br><span class="line">84</span><br><span class="line">85</span><br><span class="line">86</span><br><span class="line">87</span><br><span class="line">88</span><br><span class="line">89</span><br><span class="line">90</span><br><span class="line">91</span><br><span class="line">92</span><br><span class="line">93</span><br><span class="line">94</span><br><span class="line">95</span><br><span class="line">96</span><br><span class="line">97</span><br><span class="line">98</span><br><span class="line">99</span><br><span class="line">100</span><br><span class="line">101</span><br><span class="line">102</span><br><span class="line">103</span><br><span class="line">104</span><br><span class="line">105</span><br><span class="line">106</span><br><span class="line">107</span><br></pre></td><td class="code"><pre><span class="line"><span class="string">&quot;&quot;&quot;</span></span><br><span class="line"><span class="string">文件的读取</span></span><br><span class="line"><span class="string">打开，关闭，读，写</span></span><br><span class="line"><span class="string"></span></span><br><span class="line"><span class="string">文件的基本操作：大概可以分为三个步骤：</span></span><br><span class="line"><span class="string">①打开文件</span></span><br><span class="line"><span class="string">②读写文件</span></span><br><span class="line"><span class="string">③关闭文件</span></span><br><span class="line"><span class="string"></span></span><br><span class="line"><span class="string">注意：可以只打开和关闭文件， 不进行任何读写</span></span><br><span class="line"><span class="string"></span></span><br><span class="line"><span class="string">    ● open() 打开函数</span></span><br><span class="line"><span class="string">        功能：使用open() 可以打开一个已经存在的文件，或者创建一个新文件</span></span><br><span class="line"><span class="string">        语法： open(name,mode,encoding)</span></span><br><span class="line"><span class="string">              name : 要打开的目标文件名称的字符串（可以包含文件所在的具体路径）</span></span><br><span class="line"><span class="string">              mode : 设置打开文件的模式（访问模式）：只读，写入，追加等</span></span><br><span class="line"><span class="string">                        r:只读</span></span><br><span class="line"><span class="string">                        w:写</span></span><br><span class="line"><span class="string">                        a:追加</span></span><br><span class="line"><span class="string">              encoding :编码格式（ 推荐使用UTF-8）</span></span><br><span class="line"><span class="string">    ● read()  读取文件</span></span><br><span class="line"><span class="string">        语法： 对象.read(num)</span></span><br><span class="line"><span class="string">        参数：num 表示要从文件中读取的数据的长度(单位是字节),如果没传入num,那么就表示读取文件中所有的数据</span></span><br><span class="line"><span class="string">    ● readlines()</span></span><br><span class="line"><span class="string">        功能：可以按照行的方式把整个文件中的内容进行一次性读取，并且返回的是一个列表，其中每一行的数据为一个元素</span></span><br><span class="line"><span class="string">    ● readline()</span></span><br><span class="line"><span class="string">        功能：一次读取一行内容</span></span><br><span class="line"><span class="string">    ● close()</span></span><br><span class="line"><span class="string">        功能：关闭文件对象，也就是关闭对文件的占用</span></span><br><span class="line"><span class="string">             如果不调用 close ，同时程序没有停止运行，那么这个文件将一直被Python程序占用</span></span><br><span class="line"><span class="string">    ● with open 语法</span></span><br><span class="line"><span class="string">        功能：通过with open 的语句块中对文件进行操作</span></span><br><span class="line"><span class="string">             可以在操作完成后自动关闭close文件，避免遗忘掉close方法</span></span><br><span class="line"><span class="string">        with open(路径字符串) as f:</span></span><br><span class="line"><span class="string">            f.readlines()</span></span><br><span class="line"><span class="string">    </span></span><br><span class="line"><span class="string"></span></span><br><span class="line"><span class="string">&quot;&quot;&quot;</span></span><br><span class="line"><span class="comment"># 打开文件</span></span><br><span class="line">path = <span class="string">&quot;/Volumes/E盘/1111.txt&quot;</span></span><br><span class="line">f = <span class="built_in">open</span>(path, <span class="string">&quot;r&quot;</span>, encoding=<span class="string">&quot;UTF-8&quot;</span>)</span><br><span class="line"></span><br><span class="line"><span class="built_in">print</span>(<span class="built_in">type</span>(f))</span><br><span class="line"></span><br><span class="line"><span class="comment"># 读取文件</span></span><br><span class="line"><span class="comment"># print(f&quot;读取10个字节的结果：&#123;f.read(10)&#125;&quot;)</span></span><br><span class="line"><span class="comment"># print(f&quot;读取全部字节：&#123;f.read()&#125;&quot;)</span></span><br><span class="line"></span><br><span class="line"><span class="built_in">print</span>(<span class="string">&#x27;--------------------------&#x27;</span>)</span><br><span class="line"></span><br><span class="line"><span class="comment"># 读取文件全部行 readlines()</span></span><br><span class="line"><span class="comment"># lines = f.readlines()</span></span><br><span class="line"><span class="comment"># print(type(lines))</span></span><br><span class="line"><span class="comment"># print(lines)</span></span><br><span class="line"></span><br><span class="line"><span class="comment"># 读取单行内容</span></span><br><span class="line"><span class="comment"># line = f.readline()</span></span><br><span class="line"><span class="comment"># print(line)</span></span><br><span class="line"></span><br><span class="line"><span class="comment"># 循环</span></span><br><span class="line"><span class="keyword">for</span> x <span class="keyword">in</span> f:</span><br><span class="line">    <span class="built_in">print</span>(x)</span><br><span class="line"></span><br><span class="line"><span class="comment"># 关闭文件</span></span><br><span class="line">f.close()</span><br><span class="line"></span><br><span class="line"><span class="built_in">print</span>(<span class="string">&quot;----------------with open 方式读取，并自动关闭文件----------------------&quot;</span>)</span><br><span class="line"><span class="comment"># with open 打开文件，会自动关闭</span></span><br><span class="line"><span class="keyword">with</span> <span class="built_in">open</span>(path, <span class="string">&#x27;r&#x27;</span>, encoding=<span class="string">&#x27;utf-8&#x27;</span>) <span class="keyword">as</span> f:</span><br><span class="line">    <span class="keyword">for</span> x <span class="keyword">in</span> f:</span><br><span class="line">        <span class="built_in">print</span>(x)</span><br><span class="line"></span><br><span class="line"><span class="built_in">print</span>(<span class="string">&quot;------------------ 练习题 --------------------&quot;</span>)</span><br><span class="line"><span class="string">&quot;&quot;&quot;</span></span><br><span class="line"><span class="string">课后练习:单词计数</span></span><br><span class="line"><span class="string">通过Windows的文本编辑器软件，将如下内容,复制并保存到: word.txt,文件可以存储在任意位置</span></span><br><span class="line"><span class="string">itheima itcast python</span></span><br><span class="line"><span class="string">itheima python itcast</span></span><br><span class="line"><span class="string">beijing shanghai itheima</span></span><br><span class="line"><span class="string">shenzhen guangzhou itheima</span></span><br><span class="line"><span class="string">wuhan hangzhou itheima</span></span><br><span class="line"><span class="string">zhengzhou bigdata itheima</span></span><br><span class="line"><span class="string"> </span></span><br><span class="line"><span class="string">通过文件读取操作，读取此文件，统计itheima单词出现的次数</span></span><br><span class="line"><span class="string">&quot;&quot;&quot;</span></span><br><span class="line"></span><br><span class="line">pathload = <span class="string">&#x27;/Volumes/E盘/1111.txt&#x27;</span></span><br><span class="line"><span class="comment"># 打开文件，只读模式</span></span><br><span class="line"></span><br><span class="line">f = <span class="built_in">open</span>(pathload, <span class="string">&quot;r&quot;</span>, encoding=<span class="string">&#x27;utf-8&#x27;</span>)</span><br><span class="line"><span class="comment"># 方式1 读取全部</span></span><br><span class="line"><span class="comment"># content = f.read()</span></span><br><span class="line"><span class="comment"># counts =content.count(&quot;itheima&quot;)</span></span><br><span class="line"><span class="comment"># print(f&quot;itheima 字符串出现的次数：&#123;counts&#125;&quot;)</span></span><br><span class="line"></span><br><span class="line"><span class="comment"># 方式2 读取内容，每次一行</span></span><br><span class="line">count = <span class="number">0</span></span><br><span class="line"><span class="keyword">for</span> line <span class="keyword">in</span> f:</span><br><span class="line">    line = line.strip()  <span class="comment"># 去除开头结尾空格和换行符</span></span><br><span class="line">    words = line.split(<span class="string">&#x27; &#x27;</span>)</span><br><span class="line">    <span class="keyword">for</span> word <span class="keyword">in</span> words:</span><br><span class="line">        <span class="keyword">if</span> word == <span class="string">&quot;itheima&quot;</span>:</span><br><span class="line">            count += <span class="number">1</span></span><br><span class="line"><span class="built_in">print</span>(<span class="string">f&quot;itheima 字符串出现的次数：<span class="subst">&#123;count&#125;</span>&quot;</span>)</span><br><span class="line"><span class="comment"># 关闭文件</span></span><br><span class="line">f.close()</span><br><span class="line"></span><br></pre></td></tr></table></figure>

<h2 id="文件的写入"><a href="#文件的写入" class="headerlink" title="文件的写入"></a><strong>文件的写入</strong></h2><p><img src="https://img-blog.csdnimg.cn/f7efcb7037b04e038335ba99661afbc9.jpeg" alt="1"><br><img src="https://img-blog.csdnimg.cn/6470838d9432441f9b6b87643dec185f.jpeg" alt="2"><br><img src="https://img-blog.csdnimg.cn/d2c61895d2fa4dbdbe6c78187e542c8d.jpeg" alt="3"></p>
<h2 id="文件的追加"><a href="#文件的追加" class="headerlink" title="文件的追加"></a><strong>文件的追加</strong></h2><p><img src="https://img-blog.csdnimg.cn/a0f081b7027a4e028eb57b3ae97e03ae.jpeg" alt="1"><br><img src="https://img-blog.csdnimg.cn/6fe40dd657be4b8383823902380c7d60.jpeg" alt="2"></p>
<h2 id="综合案例"><a href="#综合案例" class="headerlink" title="综合案例"></a><strong>综合案例</strong></h2><p><img src="https://img-blog.csdnimg.cn/67241bf907104485a5d53f8e021e1956.jpeg" alt="3"><br><img src="https://img-blog.csdnimg.cn/0333d414adcc4f4fa5df0e499a786fa8.jpeg" alt="4"></p>
<blockquote>
<p>代码展示</p>
</blockquote>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br></pre></td><td class="code"><pre><span class="line"><span class="string">&quot;&quot;&quot;</span></span><br><span class="line"><span class="string">文件操作的综合案例 备份一个账单</span></span><br><span class="line"><span class="string"></span></span><br><span class="line"><span class="string"></span></span><br><span class="line"><span class="string">&quot;&quot;&quot;</span></span><br><span class="line">path = <span class="string">&quot;/Volumes/E盘/Python测试代码/&quot;</span></span><br><span class="line">filename = <span class="string">&quot;账单.txt&quot;</span></span><br><span class="line"></span><br><span class="line"><span class="comment"># 读取文件</span></span><br><span class="line">fr = <span class="built_in">open</span>(path + filename, <span class="string">&quot;r&quot;</span>, encoding=<span class="string">&quot;UTF-8&quot;</span>)</span><br><span class="line"><span class="comment"># 将文件写出到bill.txt文件</span></span><br><span class="line">fw = <span class="built_in">open</span>(path + <span class="string">&quot;账单.txt.bak&quot;</span>, <span class="string">&quot;w&quot;</span>, encoding=<span class="string">&quot;UTF-8&quot;</span>)</span><br><span class="line"><span class="comment"># 同时 将文件内标记为测试的数据进行丢弃</span></span><br><span class="line"><span class="keyword">for</span> line <span class="keyword">in</span> fr:</span><br><span class="line">    line = line.strip()  <span class="comment"># 去除手尾空格 和换行</span></span><br><span class="line">    <span class="keyword">if</span> line.split(<span class="string">&#x27;,&#x27;</span>)[<span class="number">4</span>] == <span class="string">&#x27;测试&#x27;</span>:  <span class="comment"># 通过,分割 为列表，并取出第四个下标的字符</span></span><br><span class="line">        <span class="keyword">continue</span></span><br><span class="line">    <span class="comment"># 将内容写出</span></span><br><span class="line">    fw.write(line + <span class="string">&quot;\n&quot;</span>)</span><br><span class="line"></span><br><span class="line">fr.close()</span><br><span class="line">fw.close()</span><br><span class="line"></span><br></pre></td></tr></table></figure>

<blockquote>
<p>账单.txt文件内容</p>
</blockquote>
<figure class="highlight txt"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br></pre></td><td class="code"><pre><span class="line">name, date, money, type, remarks</span><br><span class="line">周杰轮, 2022-01-01, 10000,消费,正式</span><br><span class="line">周杰轮1, 2022-01-02, 30000,收入,正式</span><br><span class="line">周杰轮2, 2022-01-03, 10000,消费,测试</span><br><span class="line">林俊节, 2022-01-01, 30000,收入,正式</span><br><span class="line">林俊节1, 2022-01-02, 10000,消费,测试</span><br><span class="line">林俊节2, 2022-01-03, 10000,消费,正式</span><br><span class="line">林俊节3, 2022-01-04, 10000,消费,测试</span><br><span class="line">林俊节4, 2022-01-05, 50000,收入,正式</span><br><span class="line">张学油, 2022-01-01, 10000,消费,正式</span><br><span class="line">张学油1, 2022-01-02, 50000,收入,正式</span><br><span class="line">张学油2, 2022-01-03, 90000,收入,测试</span><br></pre></td></tr></table></figure></article><div class="post-copyright"><div class="post-copyright__author"><span class="post-copyright-meta">文章作者: </span><span class="post-copyright-info"><a href="http://grace.666443.xyz">小妖</a></span></div><div class="post-copyright__type"><span class="post-copyright-meta">文章链接: </span><span class="post-copyright-info"><a href="http://grace.666443.xyz/posts/66462a4e.html">http://grace.666443.xyz/posts/66462a4e.html</a></span></div><div class="post-copyright__notice"><span class="post-copyright-meta">版权声明: </span><span class="post-copyright-info">本博客所有文章除特别声明外，均采用 <a href="https://creativecommons.org/licenses/by-nc-sa/4.0/" target="_blank">CC BY-NC-SA 4.0</a> 许可协议。转载请注明来自 <a href="http://grace.666443.xyz" target="_blank">小妖笔记</a>！</span></div></div><div class="tag_share"><div class="post-meta__tag-list"></div><div class="post_share"><div class="social-share" data-image="https://p.ananas.chaoxing.com/star3/origin/0ceb37b5df0be961614fe246b9d2048a.png" data-sites="facebook,twitter,wechat,weibo,qq"></div><link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/butterfly-extsrc/sharejs/dist/css/share.min.css" media="print" onload="this.media='all'"><script src="https://cdn.jsdelivr.net/npm/butterfly-extsrc/sharejs/dist/js/social-share.min.js" defer></script></div></div><div class="post-reward"><div class="reward-button"><i class="fas fa-qrcode"></i> 打赏</div><div class="reward-main"><ul class="reward-all"><li class="reward-item"><a href="https://p.ananas.chaoxing.com/star3/origin/5a01db3c5a0daca9fa2b024736bf66e3.png" target="_blank"><img class="post-qr-code-img" src="https://p.ananas.chaoxing.com/star3/origin/5a01db3c5a0daca9fa2b024736bf66e3.png" alt="微信打赏"/></a><div class="post-qr-code-desc">微信打赏</div></li><li class="reward-item"><a href="https://p.ananas.chaoxing.com/star3/origin/afffb275198370656cb6cef6a1107185.png" target="_blank"><img class="post-qr-code-img" src="https://p.ananas.chaoxing.com/star3/origin/afffb275198370656cb6cef6a1107185.png" alt="支付宝打赏"/></a><div class="post-qr-code-desc">支付宝打赏</div></li></ul></div></div><nav class="pagination-post" id="pagination"><div class="prev-post pull-left"><a href="/posts/7257d1bd.html"><img class="prev-cover" src="https://p.ananas.chaoxing.com/star3/origin/7ab42aabbf918bd08376d33683c57fc5.png" onerror="onerror=null;src='/img/404.jpg'" alt="cover of previous post"><div class="pagination-info"><div class="label">上一篇</div><div class="prev_info">10.Python异常.模块.包</div></div></a></div><div class="next-post pull-right"><a href="/posts/b515868e.html"><img class="next-cover" src="https://p.ananas.chaoxing.com/star3/origin/2be5cfbaf7fdc330fbcdbc43704e5405.png" onerror="onerror=null;src='/img/404.jpg'" alt="cover of next post"><div class="pagination-info"><div class="label">下一篇</div><div class="next_info">08.Python函数进阶</div></div></a></div></nav></div><div class="aside-content" id="aside-content"><div class="card-widget card-info"><div class="is-center"><div class="avatar-img"><img src="https://i.loli.net/2021/02/24/5O1day2nriDzjSu.png" onerror="this.onerror=null;this.src='/img/friend_404.gif'" alt="avatar"/></div><div class="author-info__name">小妖</div><div class="author-info__description">常用开发中的笔记记录</div></div><div class="card-info-data site-data is-center"><a href="/archives/"><div class="headline">文章</div><div class="length-num">28</div></a><a href="/tags/"><div class="headline">标签</div><div class="length-num">2</div></a><a href="/categories/"><div class="headline">分类</div><div class="length-num">7</div></a></div><a id="card-info-btn" target="_blank" rel="noopener" href="https://github.com/xxxxxx"><i class="fab fa-github"></i><span>Follow Me</span></a></div><div class="card-widget card-announcement"><div class="item-headline"><i class="fas fa-bullhorn fa-shake"></i><span>公告</span></div><div class="announcement_content">This is my Blog 技术笔记</div></div><div class="sticky_layout"><div class="card-widget" id="card-toc"><div class="item-headline"><i class="fas fa-stream"></i><span>目录</span><span class="toc-percentage"></span></div><div class="toc-content"><ol class="toc"><li class="toc-item toc-level-1"><a class="toc-link" href="#Python%E5%85%A5%E9%97%A8%E8%AF%BE%E7%A8%8B-%E6%96%87%E4%BB%B6%E6%93%8D%E4%BD%9C"><span class="toc-number">1.</span> <span class="toc-text">Python入门课程   文件操作</span></a><ol class="toc-child"><li class="toc-item toc-level-2"><a class="toc-link" href="#%E7%AB%A0%E8%8A%82%E7%9B%AE%E5%BD%95"><span class="toc-number">1.1.</span> <span class="toc-text">章节目录</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#%E6%96%87%E4%BB%B6%E7%9A%84%E7%BC%96%E7%A0%81"><span class="toc-number">1.2.</span> <span class="toc-text">文件的编码</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#%E6%96%87%E4%BB%B6%E7%9A%84%E8%AF%BB%E5%8F%96"><span class="toc-number">1.3.</span> <span class="toc-text">文件的读取</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#%E6%96%87%E4%BB%B6%E7%9A%84%E5%86%99%E5%85%A5"><span class="toc-number">1.4.</span> <span class="toc-text">文件的写入</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#%E6%96%87%E4%BB%B6%E7%9A%84%E8%BF%BD%E5%8A%A0"><span class="toc-number">1.5.</span> <span class="toc-text">文件的追加</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#%E7%BB%BC%E5%90%88%E6%A1%88%E4%BE%8B"><span class="toc-number">1.6.</span> <span class="toc-text">综合案例</span></a></li></ol></li></ol></div></div><div class="card-widget card-recent-post"><div class="item-headline"><i class="fas fa-history"></i><span>最新文章</span></div><div class="aside-list"><div class="aside-list-item"><a class="thumbnail" href="/posts/18ae4187.html" title="Python项目0002 - 超星小组云盘批量上传图片"><img src="http://pic.qqbizhi.com/allimg/bbpic/92/3692_4.jpg" onerror="this.onerror=null;this.src='/img/404.jpg'" alt="Python项目0002 - 超星小组云盘批量上传图片"/></a><div class="content"><a class="title" href="/posts/18ae4187.html" title="Python项目0002 - 超星小组云盘批量上传图片">Python项目0002 - 超星小组云盘批量上传图片</a><time datetime="2022-12-10T15:52:50.000Z" title="发表于 2022-12-10 23:52:50">2022-12-10</time></div></div><div class="aside-list-item"><a class="thumbnail" href="/posts/fe5af520.html" title="Python项目0001 - B站视频无水印解析"><img src="https://pic1.zhimg.com/v2-1b0b3d48f5259a87189012f8d7e9b370_r.jpg" onerror="this.onerror=null;this.src='/img/404.jpg'" alt="Python项目0001 - B站视频无水印解析"/></a><div class="content"><a class="title" href="/posts/fe5af520.html" title="Python项目0001 - B站视频无水印解析">Python项目0001 - B站视频无水印解析</a><time datetime="2022-12-10T15:17:28.000Z" title="发表于 2022-12-10 23:17:28">2022-12-10</time></div></div><div class="aside-list-item"><a class="thumbnail" href="/posts/3f24dd85.html" title="05.hexo视频教程"><img src="https://i1.hdslb.com/bfs/archive/cf6a8413b8ec8bd17612c2b48055be269b7ff496.jpg" onerror="this.onerror=null;this.src='/img/404.jpg'" alt="05.hexo视频教程"/></a><div class="content"><a class="title" href="/posts/3f24dd85.html" title="05.hexo视频教程">05.hexo视频教程</a><time datetime="2022-12-09T16:26:08.000Z" title="发表于 2022-12-10 00:26:08">2022-12-10</time></div></div><div class="aside-list-item"><a class="thumbnail" href="/posts/afee721f.html" title="0001.超星网盘直链"><img src="http://p.ananas.chaoxing.com/star3/origin/6ed6e3f7288e00f92ed58e6e018e76cd.jpg?rw=640&amp;rh=258" onerror="this.onerror=null;this.src='/img/404.jpg'" alt="0001.超星网盘直链"/></a><div class="content"><a class="title" href="/posts/afee721f.html" title="0001.超星网盘直链">0001.超星网盘直链</a><time datetime="2022-12-09T16:19:40.000Z" title="发表于 2022-12-10 00:19:40">2022-12-10</time></div></div><div class="aside-list-item"><a class="thumbnail" href="/posts/e76c3612.html" title="03.hexo文章标签配置"><img src="http://img.netbian.com/file/20150311/018c085855710a01c71d88a48a3270fe.jpg" onerror="this.onerror=null;this.src='/img/404.jpg'" alt="03.hexo文章标签配置"/></a><div class="content"><a class="title" href="/posts/e76c3612.html" title="03.hexo文章标签配置">03.hexo文章标签配置</a><time datetime="2022-12-08T13:47:38.000Z" title="发表于 2022-12-08 21:47:38">2022-12-08</time></div></div></div></div></div></div></main><footer id="footer"><div id="footer-wrap"><div class="copyright">&copy;2020 - 2022 By 小妖</div><div class="framework-info"><span>框架 </span><a target="_blank" rel="noopener" href="https://hexo.io">Hexo</a><span class="footer-separator">|</span><span>主题 </span><a target="_blank" rel="noopener" href="https://github.com/jerryc127/hexo-theme-butterfly">Butterfly</a></div><div class="footer_custom_text"><a target="_blank" rel="noopener" href='https://butterfly.js.org/'>Butterfly主题配置</a></div></div></footer></div><div id="rightside"><div id="rightside-config-hide"><button id="readmode" type="button" title="阅读模式"><i class="fas fa-book-open"></i></button><button id="darkmode" type="button" title="浅色和深色模式转换"><i class="fas fa-adjust"></i></button><button id="hide-aside-btn" type="button" title="单栏和双栏切换"><i class="fas fa-arrows-alt-h"></i></button></div><div id="rightside-config-show"><button id="rightside_config" type="button" title="设置"><i class="fas fa-cog fa-spin"></i></button><button class="close" id="mobile-toc-button" type="button" title="目录"><i class="fas fa-list-ul"></i></button><button id="go-up" type="button" title="回到顶部"><i class="fas fa-arrow-up"></i></button></div></div><div id="local-search"><div class="search-dialog"><nav class="search-nav"><span class="search-dialog-title">搜索</span><span id="loading-status"></span><button class="search-close-button"><i class="fas fa-times"></i></button></nav><div class="is-center" id="loading-database"><i class="fas fa-spinner fa-pulse"></i><span>  数据库加载中</span></div><div class="search-wrap"><div id="local-search-input"><div class="local-search-box"><input class="local-search-box--input" placeholder="搜索文章" type="text"/></div></div><hr/><div id="local-search-results"></div></div></div><div id="search-mask"></div></div><div><script src="/js/utils.js"></script><script src="/js/main.js"></script><script src="https://cdn.jsdelivr.net/npm/@fancyapps/ui/dist/fancybox.umd.min.js"></script><script src="https://cdn.jsdelivr.net/npm/node-snackbar/dist/snackbar.min.js"></script><script src="/js/search/local-search.js"></script><div class="js-pjax"><script>(() => {
  const $mermaidWrap = document.querySelectorAll('#article-container .mermaid-wrap')
  if ($mermaidWrap.length) {
    window.runMermaid = () => {
      window.loadMermaid = true
      const theme = document.documentElement.getAttribute('data-theme') === 'dark' ? 'dark' : 'default'

      Array.from($mermaidWrap).forEach((item, index) => {
        const mermaidSrc = item.firstElementChild
        const mermaidThemeConfig = '%%{init:{ \'theme\':\'' + theme + '\'}}%%\n'
        const mermaidID = 'mermaid-' + index
        const mermaidDefinition = mermaidThemeConfig + mermaidSrc.textContent
        mermaid.mermaidAPI.render(mermaidID, mermaidDefinition, (svgCode) => {
          mermaidSrc.insertAdjacentHTML('afterend', svgCode)
        })
      })
    }

    const loadMermaid = () => {
      window.loadMermaid ? runMermaid() : getScript('https://cdn.jsdelivr.net/npm/mermaid/dist/mermaid.min.js').then(runMermaid)
    }

    window.pjax ? loadMermaid() : document.addEventListener('DOMContentLoaded', loadMermaid)
  }
})()</script></div><script defer="defer" id="ribbon" src="https://cdn.jsdelivr.net/npm/butterfly-extsrc/dist/canvas-ribbon.min.js" size="150" alpha="0.6" zIndex="-1" mobile="false" data-click="false"></script><div class="fb-customerchat" id="fb-customer-chat" attribution="biz_inbox"></div><script>document.getElementById('fb-root') ? '' : document.body.insertAdjacentHTML('afterend', '<div id="fb-root"></div>')

window.fbAsyncInit = function() {
  FB.init({
    xfbml: true,
    version: 'v15.0'
  });
};

(function(d, s, id) {
  var js, fjs = d.getElementsByTagName(s)[0];
  if (d.getElementById(id)) return;
  js = d.createElement(s); js.id = id;
  js.src = 'https://connect.facebook.net/zh_CN/sdk/xfbml.customerchat.js';
  fjs.parentNode.insertBefore(js, fjs);
}(document, 'script', 'facebook-jssdk'));

if (false) {
  var chatBtnFn = () => {
    var chatBtn = document.getElementById("chat_btn")
    chatBtn.addEventListener("click", function(){
      FB.CustomerChat.show();
    });
  }
  chatBtnFn()
} else {
  if (false) {
    function chatBtnHide () {
      FB.CustomerChat.hide()
    }
    function chatBtnShow () {
      FB.CustomerChat.show(false)
    }
  }
}</script><script async data-pjax src="//busuanzi.ibruce.info/busuanzi/2.3/busuanzi.pure.mini.js"></script></div></body></html>